﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Xml;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using System.Text;

namespace TeamFoundation.EventBus
{
    public partial class Default : System.Web.UI.Page
    {
        public class EventInfo
        {
            public string EventName { get; set; }
            public string NextAction { get; set; }
            public string Id { get; set; }

            public EventInfo() { Id = "-1"; }
        }

        private bool _isInstalled;

        protected void Page_Load(object sender, EventArgs e)
        {
            _isInstalled = WebConfigurationManager.AppSettings["isInstalled"] == "true";
            _installPanel.Visible = !_isInstalled;
            _uninstallPanel.Visible = _isInstalled;
            _subscriptionsPanel.Visible = _isInstalled && User.IsInRole("Administrators");
            _queuesPanel.Visible = _subscriptionsPanel.Visible;

            _installLink.Enabled = User.IsInRole("Administrators");
            _uninstallLink.Enabled = User.IsInRole("Administrators");

            if (_isInstalled)
            {
                PopulateInstallationData();

                PopulateEvents();

                PopulateQueues();
            }
        }

        private void PopulateQueues()
        {
            _queuesPanel.DataBind();
        }

        private void PopulateEvents()
        {
            Dictionary<string, EventInfo> events = new Dictionary<string, EventInfo>();
            string[] evts = Utilities.GetEvents();
            if (evts.Length == 0)
                return;

            foreach (string evt in evts)
            {
                if (!events.ContainsKey(evt.ToLowerInvariant()))
                    events.Add(evt.ToLowerInvariant(), new EventInfo()
                    {
                        EventName = evt,
                        NextAction = "Subscribe"
                    });
            }

            using (TeamFoundationServer tfs = new TeamFoundationServer(_idTeamServer.Text))
            {
                tfs.EnsureAuthenticated();
                IEventService svc = (IEventService)tfs.GetService(typeof(IEventService));

                foreach (Subscription sub in svc.EventSubscriptions(User.Identity.Name))
                {
                    if (sub.Tag == "tfeb")
                    {
                        if (events.ContainsKey(sub.EventType.ToLowerInvariant()))
                        {
                            events[sub.EventType.ToLowerInvariant()].NextAction = "Unsubscribe";
                            events[sub.EventType.ToLowerInvariant()].Id = sub.ID.ToString();
                        }
                        else
                        {
                            events.Add(sub.EventType.ToLowerInvariant(), new EventInfo()
                            {
                                EventName = sub.EventType,
                                NextAction = "Unsusbcribe",
                                Id = sub.ID.ToString()
                            });
                        }
                    }
                }
            }

            List<EventInfo> final = new List<EventInfo>(events.Values);
            _subscriptions.DataSource = final;
            _subscriptions.DataBind();
        }

        private void PopulateInstallationData()
        {
            _idAccessUrl.Text = Utilities.DiscoverRootUrl(Request).ToString();
            _idAccessUrl.NavigateUrl = _idAccessUrl.Text;
            _idTeamServer.Text = WebConfigurationManager.AppSettings["tfServer"];
            _idTeamServer.NavigateUrl = _idTeamServer.Text;

            _idDatabaseName.Text = WebConfigurationManager.AppSettings["dbServer"];
            _idDatabaseServer.Text = WebConfigurationManager.AppSettings["dbName"];
        }


        protected void _addButton_Click(object sender, EventArgs e)
        {
            StringBuilder uri = new StringBuilder();
            uri.Append("Action.ashx?type=SubscribeAction&event=");
            uri.Append(HttpUtility.UrlEncode(_addTextBox.Text));
            uri.Append("&to=Subscribe");
            Response.Redirect(uri.ToString());
        }

        protected void OnAddQueue(object sender, EventArgs e)
        {
            System.Collections.IDictionary dic = new System.Collections.Hashtable();
            _queuesGridView.DataBind();
            _queuesGridView.EditIndex = _queuesGridView.Rows.Count;
        }

        private void UpdateValue(XmlDocument doc, string name, string xpath, string newValue)
        {
            XmlAttribute attr = (XmlAttribute)doc.SelectSingleNode(xpath);
            if (attr == null)
                throw new Exception(string.Format("'{0}' not found in configuration.", name));
            attr.Value = newValue;
        }

        protected void _queueInsertView_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
        {
            _queuesLinqDataSource.DataBind();
        }
    }
}
